 #!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2
import numpy as np
import pyautogui
import time
import os
import random
from datetime import datetime
import logging

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("binance_trading.log"),
        logging.StreamHandler()
    ]
)

class BinanceTrader:
    def __init__(self):
        self.up_button_location = None
        self.down_button_location = None
        # 上涨按钮的颜色特征 (RGB: 绿色按钮)
        self.up_button_color_lower = np.array([50, 150, 50])
        self.up_button_color_upper = np.array([100, 255, 100])
        # 下跌按钮的颜色特征 (RGB: 红色按钮)
        self.down_button_color_lower = np.array([150, 50, 50])
        self.down_button_color_upper = np.array([255, 100, 100])

    def locate_buttons(self):
        """定位上涨和下跌按钮"""
        # 截取屏幕
        screenshot = pyautogui.screenshot()
        screenshot = np.array(screenshot)
        # 转换颜色空间从RGB到BGR (OpenCV使用BGR)
        screenshot_bgr = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
        
        # 寻找绿色区域（上涨按钮）
        mask_up = cv2.inRange(
            screenshot_bgr, 
            self.up_button_color_lower, 
            self.up_button_color_upper
        )
        contours_up, _ = cv2.findContours(mask_up, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        # 寻找红色区域（下跌按钮）
        mask_down = cv2.inRange(
            screenshot_bgr, 
            self.down_button_color_lower, 
            self.down_button_color_upper
        )
        contours_down, _ = cv2.findContours(mask_down, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        
        # 找到面积最大的绿色区域作为上涨按钮
        if contours_up:
            largest_up = max(contours_up, key=cv2.contourArea)
            if cv2.contourArea(largest_up) > 5000:  # 最小面积阈值
                x, y, w, h = cv2.boundingRect(largest_up)
                self.up_button_location = (x + w//2, y + h//2)  # 按钮中心
                logging.info(f"找到上涨按钮，位置: {self.up_button_location}")
        
        # 找到面积最大的红色区域作为下跌按钮
        if contours_down:
            largest_down = max(contours_down, key=cv2.contourArea)
            if cv2.contourArea(largest_down) > 5000:  # 最小面积阈值
                x, y, w, h = cv2.boundingRect(largest_down)
                self.down_button_location = (x + w//2, y + h//2)  # 按钮中心
                logging.info(f"找到下跌按钮，位置: {self.down_button_location}")
        
        return self.up_button_location is not None and self.down_button_location is not None

    def get_price_trend(self):
        """
        分析价格趋势，返回预测
        这里只是一个示例，您需要根据您的策略实现真正的逻辑
        """
        # 这里应该是您的策略逻辑
        # 返回 1 表示看涨，-1 表示看跌，0 表示不确定
        
        # 示例：随机策略
        # return random.choice([1, -1])
        
        # 示例：简单趋势策略 (实际应用中需要替换为您的策略)
        current_hour = datetime.now().hour
        current_minute = datetime.now().minute
        
        # 这里只是一个示例条件，您需要替换为您的实际策略
        if current_minute % 2 == 0:  # 偶数分钟看涨
            return 1
        else:  # 奇数分钟看跌
            return -1

    def place_order(self, direction):
        """
        下单，direction: 1 看涨，-1 看跌
        """
        if direction == 1 and self.up_button_location:
            logging.info("执行看涨操作")
            pyautogui.click(self.up_button_location)
            return True
        elif direction == -1 and self.down_button_location:
            logging.info("执行看跌操作")
            pyautogui.click(self.down_button_location)
            return True
        else:
            logging.warning("无法执行操作，方向不明或按钮未找到")
            return False

    def run(self, interval=10):
        """
        运行交易策略
        interval: 检查间隔，单位秒
        """
        while True:
            try:
                logging.info("开始新一轮检查...")
                
                # 每次都重新定位按钮，以防界面有变化
                if not self.locate_buttons():
                    logging.warning("未能找到交易按钮，稍后重试")
                    time.sleep(5)
                    continue
                
                # 获取交易方向
                direction = self.get_price_trend()
                
                if direction != 0:
                    success = self.place_order(direction)
                    if success:
                        logging.info(f"下单成功，方向: {'看涨' if direction == 1 else '看跌'}")
                    else:
                        logging.error("下单失败")
                else:
                    logging.info("当前不满足交易条件，等待下一次检查")
                
                # 等待指定时间
                logging.info(f"等待 {interval} 秒进行下一次检查")
                time.sleep(interval)
                
            except Exception as e:
                logging.error(f"发生错误: {str(e)}")
                time.sleep(10)  # 出错后等待时间

if __name__ == "__main__":
    # 给一些时间切换到币安界面
    print("程序将在5秒后开始运行，请确保币安APP在前台显示...")
    time.sleep(5)
    
    trader = BinanceTrader()
    
    # 运行策略，每30秒检查一次
    trader.run(interval=10)